package com.rom.queue;

import java.util.Scanner;

public class CircleQueue {
    public static void main(String[] args) {
        ArrayCircleQueue arrayCircleQueue = new ArrayCircleQueue(4);
        char key = ' ';
        Scanner scanner = new Scanner(System.in);
        boolean loop = true;
        while (loop){
            System.out.println("s(show)：显示队列");
            System.out.println("e(exit)：退出程序");
            System.out.println("a(add)：添加");
            System.out.println("g(get)：取出");
            System.out.println("h(h)：查看队列头");
            key = scanner.next().charAt(0);
            switch (key){
                case 's':
                    arrayCircleQueue.showQueue();
                    break;
                case 'a':
                    System.out.println("输入一个数：");
                    int value = scanner.nextInt();
                    arrayCircleQueue.addQueue(value);
                    break;
                case 'g':
                    int queue = arrayCircleQueue.getQueue();
                    System.out.println(queue);
                    break;
                case 'h':
                    int headQueue = arrayCircleQueue.headQueue();
                    System.out.println(headQueue);
                    break;
                case 'e':
                    scanner.close();
                    loop = false;
                    break;
                default:break;
            }
        }
    }
}

//环形队列
class ArrayCircleQueue{

    private int maxSize;
    //环形队列都从0开始
    private int front;
    private int rear;

    private int[] arr;

    public ArrayCircleQueue(int arrMaxSize){
        maxSize = arrMaxSize;
        arr = new int[maxSize];
//        front = -1;
//        rear = -1;
    }
    public boolean isFull(){
        //rear指向预置位，表示队满
        return (rear+1)%maxSize == front;
    }
    public boolean isEmpty(){
        return rear == front;
    }
    //添加值到队列
    public void addQueue(int n){
        if(isFull()){
            System.out.println("队列满，不能加入数据-");
            return;
        }
        arr[rear] = n;
        rear = (rear+1)%maxSize;
    }
    //取出数据
    public int getQueue(){
        if(isEmpty()){
            throw new RuntimeException("队列空,不能取出数据");
        }
        int value = arr[front];
        front = (front+1)%maxSize;
        return value;
    }
    //数组遍历
    public void showQueue(){
        if(isEmpty()){
            System.out.println("队列空的、没有数据");
            return;
        }
        for (int i = front; i < front+size(); i++) {
            System.out.printf("arr[%d]=%d\t\n",i%maxSize,arr[i%maxSize]);
        }
    }
    //显示数组的头数据是多少
    public int headQueue(){
        if(isEmpty()){
            throw new RuntimeException("队列空的、没有数据...");
        }
        return arr[front];
    }

    public int size(){
        return (rear+maxSize-front) % maxSize;
    }
}



